import { Navigate, useParams } from "react-router-dom";
import { HStack, Box, Stack, Flex, useToast } from "@chakra-ui/react";
import { useQuery, useQueryClient } from "react-query";
import { Badge, Tag, Button, IconButton } from "@chakra-ui/react";
import { List, ListItem } from "@chakra-ui/react";
import { Text, Heading } from "@chakra-ui/react";
import { Avatar, AvatarGroup } from "@chakra-ui/react";
import { CheckIcon, CloseIcon } from "@chakra-ui/icons";
import { MainLayout } from "../components/layouts/MainLayout";
import { HomeShortcutPanel } from "../components/sections/ShortcutPanel";
import { Card } from "../components/Card";
import { MissionType } from "./Home";
import { EditMissionShortcut } from "../components/sections/ShortcutPanel";
import { CreateOrEditApplicationShortcut } from "../components/sections/ShortcutPanel";
import { CompleteMissionShortcut } from "../components/sections/ShortcutPanel";
import { Image } from "@chakra-ui/react";

export interface UserType {
  username: string;
  description: string;
  department: string;
  phone: string;
  missions: MissionType[];
  credit: string;
  level: string;
  tags: string[];
}
export interface AppType {
  id: string;
  applier: UserType;
  description: string;
  state: string;
  is_owner: boolean;
  mission: MissionType;
}

export const Mission = () => {
  const toast = useToast();
  const { missionId } = useParams<string>();
  const queryClient = useQueryClient();

  const { data: missionData } = useQuery<MissionType, any>(
    `mission/${missionId}`,
    () =>
      fetch(`/api/mission/${missionId}`, {
        headers: {
          Authorization:
            "Bearer " + String(localStorage.getItem("accessToken")),
        },
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
          return res;
        })
  );

  const { data: appData } = useQuery<AppType[], any>(
    `${missionId}/applications`,
    () =>
      fetch(`/api/mission/${missionId}/applications`, {
        headers: {
          Authorization:
            "Bearer " + String(localStorage.getItem("accessToken")),
        },
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
          return res;
        })
  );

  const { data: myAppData } = useQuery<AppType, any>(
    `${missionId}/userappliaction`,
    () =>
      fetch(`/api/user/${missionId}/application`, {
        headers: {
          Authorization:
            "Bearer " + String(localStorage.getItem("accessToken")),
        },
      })
        .then((res) => res.json())
        .then((res) => {
          if (JSON.stringify(res) === "{}") {
            return undefined;
          }
          return res;
        })
  );

  return localStorage.getItem("accessToken") ? (
    <MainLayout>
      <Flex width="100%" justify="space-between" mt={2} zIndex={1}>
        <Box width="100%" flex={7} mr={1}>
          <Card>
            <Stack spacing={4}>
              <Text fontSize="sm" color="gray.500">
                发布于{" "}
                {new Date(missionData?.created ?? "").toDateString() ===
                new Date().toDateString()
                  ? "今天"
                  : missionData?.deadline.split("T")[0]}
              </Text>
              <Heading>任务名称 #{missionData?.title}</Heading>
              <HStack>
                <Text fontSize="sm" color="gray.500">
                  任务类型
                </Text>
                <Tag>{missionData?.type}</Tag>
              </HStack>
              <HStack>
                <Text fontSize="sm" color="gray.500">
                  任务状态
                </Text>
                <Badge>{missionData?.state}</Badge>
              </HStack>
              <HStack>
                <Text fontSize="sm" color="gray.500">
                  任务人数 <Tag>{missionData?.people}</Tag>
                </Text>
              </HStack>
              <HStack>
                <Text fontSize="sm" color="gray.500">
                  任务积分 <Tag>{missionData?.credit_per_people}</Tag>
                </Text>
              </HStack>
              <HStack>
                <Text fontSize="sm" color="gray.500">
                  任务结束日期 <Tag>{missionData?.deadline.split("T")[0]}</Tag>
                </Text>
              </HStack>
              <Heading as="h2" size="md">
                任务描述
              </Heading>
              <Text>{missionData?.description}</Text>

              {missionData?.picture === "" ? (
                <></>
              ) : (
                <>
                  <Heading as="h2" size="md">
                    任务图片
                  </Heading>
                  <Image
                    objectFit="cover"
                    src={missionData?.picture}
                    alt={missionData?.title}
                  />
                </>
              )}
              {missionData?.is_owner &&
              missionData.applications?.length === 0 && missionData?.state !== "已删除" ? (
                <div>
                  <HStack>
                    <EditMissionShortcut
                      missionId={missionData?.id}
                      missionTitle={missionData?.title}
                      missionType={missionData?.type}
                      missionPeople={missionData?.people}
                      missionDeadline={missionData?.deadline}
                      missionDescription={missionData?.description}
                    />
                  </HStack>
                </div>
              ) : null}
              {appData &&
              appData.length > 0 &&
              appData.filter((x) => x.state === "同意").length > 0 ? (
                <div>
                  <Heading as="h2" size="md">
                    当前已报名
                  </Heading>
                  <AvatarGroup size="md" max={2}>
                    {appData
                      .filter((x) => x.state === "同意")
                      .map((x) => (
                        <div>
                          <Avatar
                            key={x.applier.username}
                            name={x.applier.username}
                          />
                          <Text>{x.applier.username}</Text>
                        </div>
                      ))}
                  </AvatarGroup>
                </div>
              ) : null}
              {missionData?.is_owner &&
              appData &&
              appData.filter((x) => x.state === "待处理").length > 0 ? (
                <div>
                  <Heading as="h2" size="md">
                    待处理申请
                  </Heading>
                  <List spacing={3}>
                    {appData
                      ?.filter((x) => x.state === "待处理")
                      .map((x) => (
                        <ListItem key={x.id}>
                          <Stack>
                            <Flex justify="space-between">
                              <Flex>
                                <Avatar />
                                <Box ml="3">
                                  <Heading size="md">
                                    {x.applier.username}
                                  </Heading>
                                  <Text fontSize="sm">
                                    {x.applier.description}
                                  </Text>
                                </Box>
                              </Flex>
                              <HStack>
                                <IconButton
                                  variant="outline"
                                  isRound
                                  colorScheme="green"
                                  aria-label="同意申请"
                                  icon={<CheckIcon />}
                                  onClick={() => {
                                    fetch(`/api/application/${x.id}/accept`, {
                                      method: "GET",
                                      headers: {
                                        Authorization:
                                          "Bearer " +
                                          String(
                                            localStorage.getItem("accessToken")
                                          ),
                                      },
                                    })
                                      .then((res) => {
                                        if (res.ok) {
                                          return res.json();
                                        } else {
                                          toast({ title: "接受失败" });
                                        }
                                      })
                                      .then((res) => {
                                        toast({ title: "接受成功" });
                                        queryClient.invalidateQueries(
                                          `${missionId}/applications`
                                        );
                                        console.log(res);
                                      })
                                      .catch((err) => {
                                        toast({
                                          title: "接受失败",
                                          description: err.message,
                                        });
                                      });
                                  }}
                                />
                                <IconButton
                                  variant="outline"
                                  isRound
                                  colorScheme="red"
                                  aria-label="拒绝申请"
                                  icon={<CloseIcon />}
                                  onClick={() => {
                                    fetch(`/api/application/${x.id}/decline`, {
                                      method: "GET",
                                      headers: {
                                        Authorization:
                                          "Bearer " +
                                          String(
                                            localStorage.getItem("accessToken")
                                          ),
                                      },
                                    })
                                      .then((res) => {
                                        if (res.ok) {
                                          return res.json();
                                        } else {
                                          toast({ title: "拒绝失败" });
                                        }
                                      })
                                      .then((res) => {
                                        toast({ title: "拒绝成功" });
                                        queryClient.invalidateQueries(
                                          `${missionId}/applications`
                                        );
                                        console.log(res);
                                      })
                                      .catch((err) => {
                                        toast({
                                          title: "拒绝失败",
                                          description: err.message,
                                        });
                                      });
                                  }}
                                />
                              </HStack>
                            </Flex>
                            <Text pl="16">{x.description}</Text>
                          </Stack>
                        </ListItem>
                      ))}
                  </List>
                </div>
              ) : null}

              {/* 以下是申请者界面 */}
              {missionData &&
              !missionData.is_owner &&
              missionData.state === "可申请" ? (
                <div>
                  {myAppData ? (
                    <div>
                      <Heading as="h2" size="md">
                        我的申请
                      </Heading>
                      <HStack>
                        <Text fontSize="sm" color="gray.500">
                          申请状态
                        </Text>
                        <Badge>{myAppData.state}</Badge>
                      </HStack>
                      <Text>{myAppData.description}</Text>
                      {myAppData.state === "已接受" ? (
                        <div>
                          <HStack>
                            <CompleteMissionShortcut
                              appId={myAppData.id}
                              missionId={missionData.id}
                            />
                          </HStack>
                        </div>
                      ) : null}

                      {myAppData.state === "待处理" ? (
                        <div>
                          <HStack>
                            <CreateOrEditApplicationShortcut
                              isEditing={true}
                              missionId={missionData.id}
                              applicationId={myAppData.id}
                              description={myAppData.description}
                            />
                            <Button
                              colorScheme="red"
                              lineHeight="1"
                              size="md"
                              onClick={() => {
                                fetch(`/api/application/${myAppData.id}`, {
                                  method: "DELETE",
                                  headers: {
                                    Authorization:
                                      "Bearer " +
                                      String(
                                        localStorage.getItem("accessToken")
                                      ),
                                  },
                                })
                                  .then((res) => {
                                    if (res.ok) {
                                      return res.json();
                                    } else {
                                      toast({ title: "删除失败" });
                                    }
                                  })
                                  .then((res) => {
                                    toast({ title: "删除成功" });
                                    queryClient.invalidateQueries(
                                      `${missionId}/userappliaction`
                                    );
                                    console.log(res);
                                  })
                                  .catch((err) => {
                                    toast({
                                      title: "删除失败",
                                      description: err.message,
                                    });
                                  });
                              }}
                            >
                              删除申请
                            </Button>
                          </HStack>
                        </div>
                      ) : null}
                    </div>
                  ) : null}
                  <br />
                  {!myAppData && missionData ? (
                    <div>
                      <CreateOrEditApplicationShortcut
                        missionId={missionData?.id}
                      />
                    </div>
                  ) : null}
                </div>
              ) : null}
            </Stack>
          </Card>
        </Box>
        <Stack width="100%" flex={3} ml={1}>
          <Card width="100%" pt={6} pb={6} pl={4} pr={4}>
            <Stack spacing={4}>
              <Heading size="sm">关于发布者</Heading>
              <Flex>
                <Avatar />
                <Box ml="3">
                  <Heading size="md">{missionData?.owner?.username}</Heading>
                  <Text fontSize="sm">{missionData?.owner?.description}</Text>
                </Box>
              </Flex>
            </Stack>
          </Card>
          <HomeShortcutPanel />
        </Stack>
      </Flex>
    </MainLayout>
  ) : (
    <Navigate to="/" />
  );
};
